import sys
import requests
import json
import time

# nacos的IP和端口
httpNacos = 'http://101.35.213.18:8848/'
try:
    serviceName = sys.argv[1]
except:
    raise Exception("参数1 -》 服务名称不能为空！如 -> shenghua-crm-biz")
try:
    serviceIp = sys.argv[2]
except:
    raise Exception("参数2 -》 服务实例IP不能为空！")
try:
    enabled = sys.argv[3]
    if enabled != 'true' and enabled != "false":
        raise Exception
except:
    raise Exception("参数3 -》 true(上线) || false(下线) ?")

# 登录获取token
loginUrl = httpNacos + 'nacos/v1/auth/users/login'
try:
    result = requests.post(loginUrl, data={"username": "nacos", "password": "yihui@2022"}).text
    token = json.loads(result)["accessToken"]
except:
    raise Exception("无法获取token，请检查nacos相关参数是否正确")
print("AccessToken：", token)
print("服务名称：", serviceName)
print("服务实例IP：", serviceIp)
totalRetries = 20
if enabled == 'true':
    print("服务实例上线中.....")
else:
    totalRetries = 1
    print("服务实例下线中.....")

# nacos查询单个服务实例详情
instancesParam = {"serviceName": serviceName, "accessToken": token, "clusterName": "DEFAULT",
                  "groupName": "DEFAULT_GROUP", "pageSize": "10", "pageNo": "1"}

# 服务实例上下线
isYes = 0
while isYes <= totalRetries:
    try:
        result = requests.get(httpNacos + 'nacos/v1/ns/catalog/instances', instancesParam).text
        instances = json.loads(result)["list"]
        for case in instances:
            if case["ip"] == serviceIp:
                instanceParam = {"serviceName": serviceName, "clusterName": case["clusterName"],
                                 "groupName": "DEFAULT_GROUP", "ip": serviceIp, "port": case["port"],
                                 "ephemeral": case["ephemeral"], "weight": case["weight"],
                                 "enabled": enabled, "metadata": json.dumps(case["metadata"])}
                # 服务实例上下线
                result = requests.put(httpNacos + 'nacos/v1/ns/instance', data=instanceParam, json=token).text
                break
        # 请求成功，结束循环
        if result == 'ok':
            print("操作成功！")
            break
        else:
            print("操作失败，正在重试！重试次数：", isYes)
    except:
        print("操作失败，正在重试！重试次数：", isYes)
    isYes += 1
    time.sleep(5)
